#include "hashMap_char.h"

HashMap* create_hashmap()
{
	return (HashMap*)calloc(1,sizeof(HashMap));
}
void destroy_hashmap(HashMap* map)
{
	//释放结点
	for (int i = 0; i < N; i++)
	{
		Entry* curr = map->table[i];
		while (curr != NULL)
		{
			Entry* next = curr->next;
			free(curr);
			curr = next;
		}
	}
	free(map);
}

V hashmap_get(HashMap* map, C key)
{
	int idx = hash(key);
	//遍历链表
	Entry* curr = map->table[idx];
	while (curr != NULL) {
		if (curr->key == key)
		{
			return curr->val;
		}
		curr = curr->next;
	}
	return -1;
}

void hashmap_add(HashMap* map, C key)
{
	int idx = hash(key);
	//遍历链表
	Entry* curr = map->table[idx];
	while (curr != NULL) {
		if (curr->key == key)
		{
			curr->val++;
			return;
		}
		curr = curr->next;
	}
}

V hashmap_put(HashMap* map, C key, V val)
{
	int idx = hash(key);
	//遍历链表
	Entry* curr = map->table[idx];
	while (curr != NULL )
	{
		if (curr->key == key)
		{
			V oldval = curr->val;
			curr->val = val;
			return oldval;
		}
		curr = curr->next;
	}
	Entry* entry = (Entry*)malloc(sizeof(Entry));
	if (entry == NULL)
	{
		printf("error\n");
		exit(1);
	}
	entry->key = key;
	entry->val = val;
	//头插法
	entry->next = map->table[idx];
	map->table[idx] = entry;
	
	return -1;
}

V hashmap_delete(HashMap* map, C key)
{
	int idx = hash(key);
	//遍历链表
	Entry* curr = map->table[idx];
	Entry* pre = NULL;
	while (curr != NULL)
	{
		if (curr->key == key)
		{
			//删除该结点
			if (pre == NULL)
			{
				map->table[idx] = curr->next;
			}
			else
			{
				pre->next = curr->next;
			}
			int deleteVal = curr->val;
			free(curr);
			return deleteVal;
		}
		pre = curr;
		curr = curr->next;
	}
	return -1;
}

int hash(C key)
{
	/*。。。*/
	//return h % N;//范围为0~N所以对N取模。
	int h = 0, g;
	while (*key)
	{
		h = (h << 4) + *key++;
		g = h & 0xf0000000;
		if (g)
			h ^= g >> 24;
		h &= ~g;
	}
	return h % N;
}